// 微信公众号分享
import http from '@/api/http.js'
import store from '@/store/index.js'
import { isWxClient, check_app_install } from '@/utils/utils.js'
var jweixin = require('@/utils/jweixin/index.js')

/**
 * 微信分享
 * @param {Object} typeid
 * @param {Object} shareInfo 分享默认数据 title：分享标题， desc：分享描述， link: 分享链接， litpic: 分享图标，hideShare：bool 是否禁用微信分享。
 */
export default async function(shareInfo = {}, typeid = '') {
	
	const {hideShare, url} = shareInfo
	
	// 默认不是分销商
	let isfenxiao = false,
		fxcode = '',
		hasLogin = store.state.hasLogin

	// 判断是否微信环境
	if (!isWxClient() || !check_app_install('share_wx_client')) {
		return
	}

	// 分享禁用
	if (hideShare) {
		hide_share()
		return
	}
		
	// 分销数据
	if (check_app_install('mobiledistribution') && hasLogin) {
		let res = await http({
			method: 'api/v2/distributor/get_isfenxiao'
		})
		if (res.status) {
			isfenxiao = res.data.isfenxiao
			fxcode = res.data.fxcode
		}
	}
	
	// 分享地址
	shareInfo.url = url ? url : location.href
	
	// 根据是否是分销商进行分享判断
	if (isfenxiao && fxcode) {
		shareInfo.url = addOrgToUrl(shareInfo.url, 'fxpcode', fxcode)
		// 分销商分享
		fenxiao_share(shareInfo, typeid)
	} else {
		// 普通分享
		normal_share(shareInfo, typeid)
	}

}

// 分销商分享
const fenxiao_share = async function(shareInfo = {}, typeid = '') {
	let {title, desc, litpic, price, url} = shareInfo
	let params = {
		method: 'api/v2/share/share_wx_fenxiao_info',
		type_id: typeid,
		url,
		title,
		desc,
		litpic,
		price
	}
	
	let res = await http(params)
	
	if (res.status) {
		let shareConfig = res.data
		let {default: shareDefault} = shareConfig
		let shareData = {
			title: shareDefault.title,
			desc: shareDefault.desc,
			url: shareConfig.url,
			litpic: shareDefault.litpic
		}
		
		// 微信分享
		jweixin_share(shareConfig, shareData)
	}
}

// 普通分享
const normal_share = async function(shareInfo = {}, typeid = '') {
	let { url, title, desc, litpic} = shareInfo
	let params = {
		method: 'api/v2/share/share_wx_info',
		typeid,
		url
	}
	
	let res = await http(params)
	
	if (res.status) {
		let shareConfig = res.data,
			shareDefault = shareConfig.default,
			shareData = {
				title: title ? title : shareDefault.title,
				desc: desc ? desc : shareDefault.desc,
				url,
				litpic: litpic ? litpic : shareDefault.litpic
			}

		// 微信分享
		jweixin_share(shareConfig, shareData)
	}
}

// 禁用分享
const hide_share = async function() {
	let url = location.href
	let params = {
		method: 'api/v2/share/share_wx_info',
		url,
	}

	let res = await http(params)
	
	if (res.status) {
		let {appid: appId, timestamp, noncestr: nonceStr, signature} = res.data
		jweixin.config({
			debug: false,
			appId, // 必填，公众号的唯一标识
			timestamp, // 必填，生成签名的时间戳
			nonceStr, // 必填，生成签名的随机串
			signature, // 必填，签名，见附录1
			jsApiList: [
				'hideMenuItems'
			]
		})

		jweixin.ready(function() {
			// 禁止分享
			jweixin.hideMenuItems({ // 要隐藏的菜单项，只能隐藏“传播类”和“保护类”按钮，所有menu项见附录3
				menuList: [
					'menuItem:share:appMessage',
					'menuItem:share:timeline',
					'menuItem:share:qq',
					'menuItem:favorite',
					'menuItem:share:QZone',
					'menuItem:openWithSafari'
				],
				success: function (res) {
					
				},
				fail: function (res) {
					
				}
			})
		})
		
	}
}

// 给url添加参数
const addOrgToUrl = function(url, paramName, replaceVal) {
	//url:路径地址 paramName：参数名 replaceWith：参数值
	if (url.indexOf(paramName) > -1) {
		let re = eval('/(' + paramName + '=)([^&]*)/gi')
		url = url.replace(re, paramName + '=' + replaceVal)
	} else {
		let paraStr = paramName + '=' + replaceVal
		let idx = url.indexOf('?')
		if (idx < 0){
			url += '?'
		}else if (idx >= 0 && idx != url.length - 1){
			url += '&'
		}
		url += paraStr
	}
	return url
}

const jweixin_share = function(shareConfig, shareData) {
	const {appid: appId, timestamp, noncestr: nonceStr, signature} = shareConfig
	const {title: shareTitle, desc: shareDesc, url: shareLink, litpic: shareImgUrl} = shareData
	
	jweixin.config({
		debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
		appId, // 必填，公众号的唯一标识
		timestamp, // 必填，生成签名的时间戳
		nonceStr, // 必填，生成签名的随机串
		signature, // 必填，签名，见附录1
		jsApiList: ['updateAppMessageShareData', 'updateTimelineShareData', 'onMenuFavorite']
	});

	jweixin.ready(function() {
		
		// 自定义“分享给朋友”及“分享到QQ”按钮的分享内容
		jweixin.updateAppMessageShareData({ 
		    title: shareTitle, // 分享标题
		    desc: shareDesc, // 分享描述
		    link: shareLink, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
		    imgUrl: shareImgUrl, // 分享图标
		    success: function () {
		      // 设置成功
		    }
		})
		
		jweixin.updateTimelineShareData({ 
		    title: shareTitle, // 分享标题
		    link: shareLink, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
		    imgUrl: shareImgUrl, // 分享图标
		    success: function () {
		      // 设置成功
		    }
		})
		
	});
}
